package com.atguigu.gulimall.product.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@EnableConfigurationProperties(CacheProperties.class)
@EnableCaching
@Configuration
public class MyRedisCacheConfiguration {
    @Autowired
    CacheProperties cacheProperties;
    /**
     * 配置文件中的东西没有用上
     *
     * 1、原来和配置文件绑定的配置类是这样子的
     *     @ConfigurationProperties(prefix = "spring.cache")
     *     public class CacheProperties
     *
     * 2、让其生效：@EnableConfigurationProperties(CacheProperties.class)
     *
     * 我们最终实现效果就是：：： 建了一个自己的配置类，实现自动注入RedisCacheConfiguration
     *      并且实现了源码中默认部分没有的部分：修改序列化方式
     *      然后引入原本的配置类，读取我们配置文件原本设置的项
     * @return
     */
    @Bean
    RedisCacheConfiguration redisCacheConfiguration(){
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //比如我改TTL
        //config = config.entryTtl(Duration.ofMinutes(60));
        //下列构造器是从RedisCacheConfiguration里面对应set函数使用的参数去找的
        //去找对应的实现接口 然后在接口按Ctrl+H 查看其全部实现类有哪些，然后选择一个比较好用的
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        //value序列化改成了json
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        //将配置文件中的所有配置都生效，也就是源码里面这一段
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }
}
